package com.point.community;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.demo.bean.PageBean;
import com.alibaba.dubbo.demo.SysDeptInfoInterface;
import com.alibaba.dubbo.demo.bean.SysDeptInfo;
import com.point.community.bean.DeptLookUpItem;
import com.point.community.bean.DeptNode;
import com.point.community.bean.dwzPageData;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@SuppressWarnings("serial")
public class SysDeptInfoAction extends JsonAction {
	
	Logger logger = Logger.getLogger(SysDeptInfoAction.class);
	
	private String msg = "";
	private boolean success = false;
	private String key = "";
	private String obj = "";
	private PageBean pageBean;
	private String statusCode,message,navTabId,rel,callbackType,forwardUrl,confirmMsg;
	
	private List<SysDeptInfo> sysDeptinfoList = new ArrayList<SysDeptInfo>();
	private List<DeptLookUpItem> sysLookupDeptList = new ArrayList<DeptLookUpItem>();
	private List<DeptNode> deptNodeList = new ArrayList<DeptNode>();
	@Autowired
	private SysDeptInfoInterface sysDeptInfoService;
	
	private SysDeptInfo sysDeptInfo = new SysDeptInfo();
	
	public SysDeptInfoInterface getSysDeptInfoService() {
		return sysDeptInfoService;
	}

	public void setSysDeptInfoService(SysDeptInfoInterface sysDeptInfoService) {
		this.sysDeptInfoService = sysDeptInfoService;
	}
	
	public Logger getLogger() {
		return logger;
	}

	public void setLogger(Logger logger) {
		this.logger = logger;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getObj() {
		return obj;
	}

	public void setObj(String obj) {
		this.obj = obj;
	}

	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	public List<SysDeptInfo> getSysDeptinfoList() {
		return sysDeptinfoList;
	}

	public void setSysDeptinfoList(List<SysDeptInfo> sysDeptinfoList) {
		this.sysDeptinfoList = sysDeptinfoList;
	}
	
	public List<DeptNode> getDeptNodeList() {
		return deptNodeList;
	}

	public void setDeptNodeList(List<DeptNode> deptNodeList) {
		this.deptNodeList = deptNodeList;
	}

	public SysDeptInfo getSysDeptInfo() {
		return sysDeptInfo;
	}

	public void setSysDeptInfo(SysDeptInfo sysDeptInfo) {
		this.sysDeptInfo = sysDeptInfo;
	}

	public List<DeptLookUpItem> getSysLookupDeptList() {
		return sysLookupDeptList;
	}

	public void setSysLookupDeptList(List<DeptLookUpItem> sysLookupDeptList) {
		this.sysLookupDeptList = sysLookupDeptList;
	}

	
	
	public String getStatusCode() {
		return statusCode;
	}
	public void setStatusCode(String statusCode) {
		this.statusCode = statusCode;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getNavTabId() {
		return navTabId;
	}
	public void setNavTabId(String navTabId) {
		this.navTabId = navTabId;
	}
	public String getRel() {
		return rel;
	}
	public void setRel(String rel) {
		this.rel = rel;
	}
	public String getCallbackType() {
		return callbackType;
	}
	public void setCallbackType(String callbackType) {
		this.callbackType = callbackType;
	}
	public String getForwardUrl() {
		return forwardUrl;
	}
	public void setForwardUrl(String forwardUrl) {
		this.forwardUrl = forwardUrl;
	}
	public String getConfirmMsg() {
		return confirmMsg;
	}
	public void setConfirmMsg(String confirmMsg) {
		this.confirmMsg = confirmMsg;
	}
	/**
	 * 获取所有部门信息
	 * 
	 * @return
	 */
	public String webQueryAllDeptInfo() {
		logger.error(" com.point.community webQueryAllDeptInfo");

		String currentPage = request.getParameter("pageNum");
		String numPerPage = request.getParameter("numPerPage");
		
		boolean all = false;
		String deptcode = "";
		if(request.getParameter("deptcode")!=null)
			deptcode = request.getParameter("deptcode");
		if(StringUtils.isEmpty(deptcode))
			deptcode = "0";
		
		String deptname = "";
		if(request.getParameter("deptname")!=null)
			deptname = request.getParameter("deptname");
		
		if(StringUtils.isEmpty(currentPage)){
			currentPage = "1";
	    }
	    if(StringUtils.isEmpty(numPerPage)){
	    	numPerPage = "20";
	    }
	    int nCurrentPage =  Integer.parseInt(currentPage);    
	    int nNumPerPage =  Integer.parseInt(numPerPage);  
	    if(request.getParameter("all")!=null)
	    {
	    	if(request.getParameter("all").toString().equals("1"))
	    		all=true;
	    }
			
		List<SysDeptInfo> datas = sysDeptInfoService.queryDeptTree(all,Integer.valueOf(deptcode), deptname);
		int totalCount = datas.size();
		int nEndPage = totalCount%nNumPerPage==0?totalCount/nNumPerPage:totalCount/nNumPerPage+1;
		
		int nStart = (nCurrentPage - 1)*nNumPerPage;
		if(nStart>totalCount)
		{
			nCurrentPage = nEndPage;
			nStart = (nCurrentPage - 1)*nNumPerPage;
		}
				
		if(datas!=null){
			for(int i=0;i<datas.size()&&i<Integer.valueOf(numPerPage);i++)
			sysDeptinfoList.add(datas.get(i));
		}
		request.getSession().setAttribute("sysDeptinfoList", sysDeptinfoList);
		logger.error("deptcode  =="+deptcode);
		if(deptcode.equals("0"))
			request.getSession().setAttribute("deptcode", "");
		else
			request.getSession().setAttribute("deptcode", deptcode);
		
		request.getSession().setAttribute("deptname", deptname);
		
		dwzPageData dwz = new dwzPageData();
		dwz.currentPage = Integer.valueOf(nCurrentPage).toString();
		dwz.numPerPage =  Integer.valueOf(nNumPerPage).toString();
		dwz.totalCount = (long) totalCount;
		request.getSession().setAttribute("deptInfoDwzData", dwz);
		return "deptinfo";
	}

	
	public String jsonQueryAllDeptInfo() {
		sysDeptinfoList = sysDeptInfoService.queryAllDeptInfoList(false);
		if (sysDeptinfoList.size() > 0) {
			success = true;
			msg = "请求成功！";
		} else {
			success = false;
			msg = "请求失败或无数据！";
		}
		return SUCCESS;
	}
	
	public String webQueryDeptInfoLookup()
	{
		logger.error(" com.point.community webQueryDeptInfoLookup");

		String currentPage = request.getParameter("pageNum");
		String numPerPage = request.getParameter("numPerPage");
		
		boolean all = false;
		String deptcode = "";
		if(request.getParameter("deptcode")!=null)
			deptcode = request.getParameter("deptcode");
		if(StringUtils.isEmpty(deptcode))
			deptcode = "0";
		
		String deptname = "";
		if(request.getParameter("deptname")!=null)
			deptname = request.getParameter("deptname");
		
		if(StringUtils.isEmpty(currentPage)){
			currentPage = "1";
	    }
	    if(StringUtils.isEmpty(numPerPage)){
	    	numPerPage = "20";
	    }
	    int nCurrentPage =  Integer.parseInt(currentPage);    
	    int nNumPerPage =  Integer.parseInt(numPerPage);  
	    
			
		List<SysDeptInfo> datas = sysDeptInfoService.queryDeptTree(all,Integer.valueOf(deptcode), deptname);
		int totalCount = datas.size();
		int nEndPage = totalCount%nNumPerPage==0?totalCount/nNumPerPage:totalCount/nNumPerPage+1;
		
		int nStart = (nCurrentPage - 1)*nNumPerPage;
		if(nStart>totalCount)
		{
			nCurrentPage = nEndPage;
			nStart = (nCurrentPage - 1)*nNumPerPage;
		}
				
		if(datas!=null){
			for(int i=0;i<datas.size()&&i<Integer.valueOf(numPerPage);i++)
			sysDeptinfoList.add(datas.get(i));
		}
		request.getSession().setAttribute("sysDeptinfoListLK", sysDeptinfoList);
		logger.error("deptcode  =="+deptcode);
		if(deptcode.equals("0"))
			request.getSession().setAttribute("deptcode", "");
		else
			request.getSession().setAttribute("deptcode", deptcode);
		
		request.getSession().setAttribute("deptname", deptname);
		
		dwzPageData dwz = new dwzPageData();
		dwz.currentPage = Integer.valueOf(nCurrentPage).toString();
		dwz.numPerPage =  Integer.valueOf(nNumPerPage).toString();
		dwz.totalCount = (long) totalCount;
		request.getSession().setAttribute("deptInfoDwzDataLK", dwz);
		
		return "deptInfoLookup";
	}
	
	public String jsonQueryDeptInfoLookup() {
		sysDeptinfoList = sysDeptInfoService.queryAllDeptInfoList(false);
		if (sysDeptinfoList.size() > 0) {
			for(int i=0;i<sysDeptinfoList.size();i++)
			{
				DeptLookUpItem item = new DeptLookUpItem();
				SysDeptInfo deptinfo = sysDeptinfoList.get(i);
				item.setId(i+1);
				item.setDeptid(deptinfo.getDeptid());
				item.setDeptname(deptinfo.getDeptname());
				item.setManager(deptinfo.getManager());
				item.setLookupUpperNum(deptinfo.getUpperid());
				sysLookupDeptList.add(item);
			}
			
			success = true;
			msg = "请求成功！";
		} else {
			success = false;
			msg = "请求失败或无数据！";
		}
		return SUCCESS;
	}
	/**
	 * 按照上级部门查询子部门信息
	 * 
	 * @return
	 */
	public String webQueryDeptInfoByUpperDept() {
		String currentPage = request.getParameter("pageNum");
		String numPerPage = request.getParameter("numPerPage");
		
		String deptrightids = request.getParameter("deptrightids");
		String deptcode = "";
		if(request.getParameter("deptcode")!=null)
			deptcode = request.getParameter("deptcode");
		if(StringUtils.isEmpty(deptcode))
			deptcode = "0";
		
		String deptname = "";
		if(request.getParameter("deptname")!=null)
			deptname = request.getParameter("deptname");
		
		if(StringUtils.isEmpty(currentPage)){
			currentPage = "1";
	    }
	    if(StringUtils.isEmpty(numPerPage)){
	    	numPerPage = "20";
	    }
	    int nCurrentPage =  Integer.parseInt(currentPage);    
	    int nNumPerPage =  Integer.parseInt(numPerPage);  
	    if(request.getParameter("all")!=null)
	    {
	    	if(request.getParameter("all").toString().equals("1")) {
			}
	    }
			
	    int nUpperId = 0;
	    List<SysDeptInfo> datas = sysDeptInfoService.queryDeptInfoListByUpperDept(false,nUpperId);
		int totalCount = datas.size();
		int nEndPage = totalCount%nNumPerPage==0?totalCount/nNumPerPage:totalCount/nNumPerPage+1;
		
		int nStart = (nCurrentPage - 1)*nNumPerPage;
		if(nStart>totalCount)
		{
			nCurrentPage = nEndPage;
			nStart = (nCurrentPage - 1)*nNumPerPage;
		}
		logger.error("Integer.valueOf(numPerPage)+"+Integer.valueOf(numPerPage));		
		if(datas!=null){
			for(int i=0;i<datas.size()&&i<Integer.valueOf(numPerPage);i++)
			sysDeptinfoList.add(datas.get(i));
		}
		
		request.getSession().setAttribute("sysUpperDept", sysDeptinfoList);
		
		logger.error("deptcode  =="+deptcode);
		if(deptcode.equals("0"))
			request.getSession().setAttribute("deptcode", "");
		else
			request.getSession().setAttribute("deptcode", deptcode);
		
		request.getSession().setAttribute("deptname", deptname);
		request.getSession().setAttribute("deptrightids", deptrightids);

		dwzPageData dwz = new dwzPageData();
		dwz.currentPage = Integer.valueOf(nCurrentPage).toString();
		dwz.numPerPage =  Integer.valueOf(nNumPerPage).toString();
		dwz.totalCount = (long) sysDeptinfoList.size();
		request.getSession().setAttribute("upperDeptDwzData", dwz);
		return "sysUpperDept";
	}

	public String jsonQueryDeptInfoByUpperDept() {
		JSONObject jsonObj = getJsonObjFromRequest();
		int nUpperId = jsonObj.getInt("upperid");
		sysDeptinfoList = sysDeptInfoService.queryDeptInfoListByUpperDept(false,nUpperId);
		if (sysDeptinfoList.size() > 0) {
			success = true;
			msg = "请求成功！";
		} else {
			success = false;
			msg = "请求失败或无数据！";
		}
		return SUCCESS;
	}

	/**
	 * 按照部门ID查询部门信息
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String webQueryDeptInfo() {
		String start = getParameterString("start");
		if (start != null && !start.equals("")) {
			pageBean = new PageBean(start, PAGE_MAX_RECORD_COUNT);
		} else {
			pageBean = new PageBean("0", PAGE_MAX_RECORD_COUNT);
		}
		int nDeptId = getParameterInteger("deptid");
		pageBean = sysDeptInfoService.queryDeptInfoByUpperDept(false,nDeptId);

		sysDeptinfoList = pageBean.getResultList();

		request.getSession().setAttribute("sysDeptinfoList", sysDeptinfoList);
		request.getSession().setAttribute("total", pageBean.getTotal());
		request.getSession().setAttribute("endPage", pageBean.getEndPage());
		request.getSession().removeAttribute("pageNo");

		return "sysDeptinfoList";
	}

	public String jsonQueryDeptInfo() {
		JSONObject jsonObj = getJsonObjFromRequest();
		int nDeptId = jsonObj.getInt("deptid");
		sysDeptinfoList = sysDeptInfoService.queryDeptInfoListByUpperDept(false,nDeptId);
		if (sysDeptinfoList.size() > 0) {
			success = true;
			msg = "请求成功！";
		} else {
			success = false;
			msg = "请求失败或无数据！";
		}
		return SUCCESS;
	}

	public String webQueryOneDept()
	{
		String sdeptid = getParameterString("deptid");
		int deptid = Integer.parseInt(sdeptid);
		SysDeptInfo deptinfo = sysDeptInfoService.queryOneDeptInfoByDept(deptid);	
		request.getSession().setAttribute("sysDeptInfo", deptinfo);
		return "queryonedept";
	}
	
	/**
	 * 保存部门信息
	 */
	public String saveDeptInfo() {
		int upperid = 0;
		if(getParameterInteger("upperid")!=null)
			upperid = getParameterInteger("upperid");
		if(getParameterInteger("orgLookup.deptid")!=null)
			upperid = getParameterInteger("orgLookup.deptid");
		sysDeptInfo.setUpperid(upperid);
		sysDeptInfo.setDeptname(getParameterString("deptname"));
		sysDeptInfo.setManager(getParameterString("manager"));
		sysDeptInfo.setPhone(getParameterString("phone"));
		sysDeptInfo.setRemark(getParameterString("remark"));
		sysDeptInfo.setIsvalid(1);
		sysDeptInfo.setChildnum(0);
		SysDeptInfo upperdept = sysDeptInfoService.queryOneDeptInfoByDept(upperid);
		if(upperid==0)
			sysDeptInfo.setDeptlevel(0);
		else
			sysDeptInfo.setDeptlevel(upperdept.getDeptlevel()+1);
		boolean ret = sysDeptInfoService.saveDeptInfo(sysDeptInfo);
		if (ret) 
		   {
				success = true;
				logger.info("保存部门信息成功!");
				
				statusCode="200";
				message="操作成功";
				navTabId="deptinfo";
				rel="";
				callbackType="closeCurrent";
				forwardUrl="";
				confirmMsg="";
			}
		   else
		   {
			    success = false;
				logger.info("保存部门信息异常!");
				
				statusCode="200";
				message="操作失败";
				navTabId="deptinfo";
				rel="";
				callbackType="closeCurrent";
				forwardUrl="";
				confirmMsg="";
		   }
		msg = "保存部门信息异常！";
		request.getSession().setAttribute("errMsg", msg);
		return SUCCESS;
	}

	/**
	 * 更新部门信息
	 */
	public String updateDeptInfo() {
		int deptid = getParameterInteger("deptid");
		sysDeptInfo = sysDeptInfoService.queryOneDeptInfoByDept(deptid);
		sysDeptInfo.setDeptname(getParameterString("deptname"));
		sysDeptInfo.setManager(getParameterString("manager"));
		sysDeptInfo.setPhone(getParameterString("phone"));
		sysDeptInfo.setRemark(getParameterString("remark"));
		logger.error(sysDeptInfo.getDeptid());
		logger.error(sysDeptInfo.getUpperid());
		logger.error(sysDeptInfo.getDeptname());
		boolean ret = sysDeptInfoService.updateDeptInfo(sysDeptInfo);
		if (ret) {
			success = true;
			logger.info("更新部门信息成功!");

			statusCode = "200";
			message = "操作成功";
			navTabId = "deptinfo";
			rel = "";
			callbackType = "closeCurrent";
			forwardUrl = "";
			confirmMsg = "";
		} else {
			success = false;
			logger.info("更新部门信息异常!");

			statusCode = "200";
			message = "操作失败";
			navTabId = "deptinfo";
			rel = "";
			callbackType = "closeCurrent";
			forwardUrl = "";
			confirmMsg = "";
			msg = "更新部门信息异常！";
			request.getSession().setAttribute("errMsg", msg);
		}
		return SUCCESS;
	}
	//更新部门状态标志
	public String updateDeptInfoFlag()
	{
		int deptid = getParameterInteger("deptid");
		sysDeptInfo = sysDeptInfoService.queryOneDeptInfoByDept(deptid);
		int valid = getParameterInteger("valid");
		sysDeptInfo.setIsvalid(valid);
		boolean ret = sysDeptInfoService.updateDeptInfo(sysDeptInfo);
		
		if (ret) 
		   {
				success = true;
				logger.info("更新部门信息成功!");
				
				statusCode="200";
				message="操作成功";
				navTabId="deptinfo";
				rel="";
				callbackType="";
				forwardUrl="";
				confirmMsg="";
			}
		   else
		   {
			    success = true;
				logger.info("更新部门信息异常!");
				
				statusCode="200";
				message="操作失败";
				navTabId="deptinfo";
				rel="";
				callbackType="";
				forwardUrl="";
				confirmMsg="";
		   }
		return SUCCESS;
	}
	/**
	 * 删除部门信息
	 */
	public String deleteDeptInfo() {
		sysDeptInfo.setUpperid(getParameterInteger("upperid"));
		sysDeptInfo.setDeptname(getParameterString("deptname"));
		sysDeptInfo.setPhone(getParameterString("phone"));
		sysDeptInfo.setRemark(getParameterString("remark"));
		boolean ret = sysDeptInfoService.deleteDeptInfo(sysDeptInfo);
		if (ret) {
			success = true;
			webQueryAllDeptInfo();
			logger.info("删除部门信息成功!");
			return "sysDeptinfo";
		}
		msg = "删除部门信息异常！";
		request.getSession().setAttribute("errMsg", msg);
		return "error";
	}
	
	//type:dept,仅部门树,dev,设备树
	//lastnodelink:true,false,是否只有子节点有超连接
	public boolean getDeptTree(int upperid,String ref,String type,String url,String lastnodelink)
	{
		//List<DeptNode> deptnodeTempList = new ArrayList<DeptNode>();
		List<SysDeptInfo> deptList = sysDeptInfoService.queryDeptInfoListByUpperDept(false,upperid);
		
		boolean noChild = true;
		if(deptList==null)
		{
			noChild = true;
		}
		else
		{
			if(deptList.size()<1)
				noChild = true;
			else
				noChild = false;
		}
		if(noChild)
		{
			if(type.equalsIgnoreCase("dept"))
				return false;
			else
			{
				return true;
			}
		}
		for(int i=0;i<deptList.size();i++)
		{
			SysDeptInfo dept = deptList.get(i);
			DeptNode deptNode = new DeptNode();
			deptNode.setId(dept.getDeptid());
			deptNode.setpId(dept.getUpperid());
			deptNode.setName(dept.getDeptname());
			deptNode.setRel(ref);
			String longUrl = url+"?deptid="+dept.getDeptid()+"&deptname="+dept.getDeptname()+"&upperid="+dept.getUpperid();
		    deptNode.setUrl(longUrl);
		    deptNode.setHaschild(true);
		    //节点类型   0:部门  1:设备
		    deptNode.setType(0);
		    deptNodeList.add(deptNode);
		    int nSize = deptNodeList.size();
		    boolean haschild = getDeptTree(dept.getDeptid(),ref,type,url,lastnodelink);
		    if(haschild)
		    {
		    	deptNodeList.get(nSize-1).setHaschild(true);	
		    	if(lastnodelink.equalsIgnoreCase("true"))
		    		deptNodeList.get(nSize-1).setUrl("");
		    }
		    else
		    {
		    	deptNodeList.get(nSize-1).setHaschild(false);
		    }
		}
		
		return true;
	}
	
	/**
	 * 获取部门树信息
	 */
	public String webGetDeptTree()
	{
		logger.error("call webGetDeptTree");
		String rel = getParameterString("rel");
		String type = getParameterString("type");
		String url = getParameterString("url");
		String lastnodelink = getParameterString("lastnodelink");
		String jsp = getParameterString("jsp");
		getDeptTree(0,rel,type,url,lastnodelink);
		request.getSession().setAttribute("deptNodeList", deptNodeList);
		logger.error("webGetDeptTree JSONArray.fromObject----------1");
		JSONArray jsonDeptNodeList = JSONArray.fromObject(deptNodeList);
		logger.error("webGetDeptTree JSONArray.fromObject----------2");
		request.getSession().setAttribute("jsonDeptNodeList", jsonDeptNodeList.toString());
		logger.error("webGetDeptTree jsp="+jsp);
		logger.error("webGetDeptTree strjsonDeptNodeList="+jsonDeptNodeList);
		if(deptNodeList.size()>0)
			return jsp;
		else
			return "error";
	}
	
	public String jsonGetDeptTree()
	{
		logger.error("enter jsonGetDeptTree");
		String rel = getParameterString("rel");
		String type = getParameterString("type");
		String url = getParameterString("url");
		String lastnodelink = getParameterString("lastnodelink");
		getDeptTree(0,rel,type,url,lastnodelink);
		if (deptNodeList.size() > 0) {
			success = true;
			msg = "请求成功！";
		} else {
			success = false;
			msg = "请求失败或无数据！";
		}
		return SUCCESS;
	}
}
